<template>
    <el-dialog v-model="dialogFormVisible" :title="title" @close="closeDialog" style="width: 600px;">
        <el-form :model="meetingForm" ref="meetingRef" :rules="meetingRules">
            <el-form-item label="会议名称" prop="meetName">
                <el-input v-model="meetingForm.meetName" autocomplete="off" placeholder="请输入会议名称"></el-input>
            </el-form-item>
            <el-form-item label="开会时间" prop="startTime">
                <el-config-provider :locale="locale">
                    <el-date-picker v-model="meetingForm.startTime" type="date" value-format="YYYY-MM-DD"
                        placeholder="选择日期" style="width:100%" />
                </el-config-provider>
            </el-form-item>
            <el-form-item label="会议类型" prop="startTime">
                <el-select v-model="meetingForm.type" placeholder="请选择会议类型" style="width:100%" @change="handle">
                    <el-option label="普通会议" :value="1" />
                    <el-option label="指定会议" :value="2" />
                </el-select>
            </el-form-item>
            <el-form-item label="开会人员" prop="participants" v-if="this.meetingForm.type === 1">
                <el-tree :props="props" show-checkbox :data="participants" ref="dataTree" node-key="userId"
                    @check="getCheckedList" />
            </el-form-item>
            <el-form-item label="开会人员" prop="participants" v-if="this.meetingForm.type === 2">
                <el-button type="primary" style="margin-bottom: 10px;width: 200px;" @click="toExcel">下载曾用民模版</el-button>
                <el-button type="primary" style="margin-bottom: 10px;width: 200px;"
                    @click="toExcel1">下载会议人员模版</el-button>
                <el-upload ref="upload" class="upload-demo" :limit="1" :auto-upload="false" :on-change="fileChange"
                    style="width: 100%;">
                    <template #trigger>
                        <el-button type="primary" style="margin-right: 10px;width: 200px;">选择文件</el-button>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer style="width:400px">
            <span class="dialog-footer">
                <el-button @click="clear()">取消</el-button>
                <el-button type="primary" @click="save">保存</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
import { ref } from "vue";
import { httpService } from "@/utils/httpService";
import { ElMessage, ElForm, ElTree } from "element-plus";
import { vxRule } from "@/utils/validator";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import * as XLSX from 'xlsx';
import XLSXS from "xlsx-style"
import FileSaver from 'file-saver';



export default {
    name: "teacher",
    components: {
        ElForm,
        ElMessage,
        ElTree,
    },
    setup() {
        return {
            locale: zhCn,
        };
    },
    data() {
        return {
            dialogFormVisible: ref(false),
            meetingRef: "",
            dataTree: "",
            props: {
                children: 'childrenList',
                label: 'name',
                isLeaf: 'leaf',
                level: 'level'
            },
            meetingForm: {
                meetId: "",
                meetName: "",
                startTime: "",
                type: "",
                participants: []
            },
            flag: false,
            holidayNumbers: [],
            currentNode: "",
            // 校验规则
            meetingRules: {
                meetName: vxRule(true, null, "blur"),
                startTime: vxRule(true, null, "blur"),
                type: vxRule(true, null, "blur"),
                participants: vxRule(true, null, "blur"),
            },
        };
    },
    mounted() {
        this.loadNode()
    },
    methods: {
        handle() {
            console.log(this.meetingForm.type);
        },
        getCheckedList() {
            this.meetingForm.participants = this.$refs.dataTree.getCheckedKeys();
        },
        loadNode() {
            httpService(
                "/pythonApi/attendanceApi/teacherTree",
                {},
                "get"
            ).then((data) => {
                this.participants = data.list;
            });
        },
        closeDialog() {
            this.clear();
        },
        cancel() {
            this.clear();
        },
        clear() {
            this.dialogFormVisible = false;
            if (this.$refs.dataTree) {
                this.$refs.dataTree.setCheckedNodes([], false, false);
            }
            this.meetingForm.meetName = "";
            this.meetingForm.startTime = "";
            this.meetingForm.participants = []
            this.flag = false
            if (this.$refs.upload) {
                this.$refs.upload.clearFiles()
            }
            this.meetingForm.type = ""
        },
        getMeetingById(meetId) {
            httpService("/pythonApi/attendanceApi/getMeetingList",
                {
                    page: 1,
                    limit: 2,
                    meetId: meetId,
                }, "get").then(
                    (data) => {
                        let temp = data.data;
                        this.meetingForm = temp[0];
                        let participants = this.meetingForm.participants;
                        for (let i in participants) {
                            this.$refs.dataTree.setChecked(participants[i], true, true)
                        }
                    }
                );
        },
        save() {
            this.$refs.meetingRef.validate((valid) => {
                if (valid) {
                    let info = [], bool = [];
                    if (this.meetingForm.type == 1) {
                        let lists = this.$refs.dataTree.getCheckedNodes(false, false)
                        for (let i in lists) {
                            let list = lists[i];
                            if (bool[list['father']]) {
                                bool[list['userId']] = true
                            } else {
                                info.push(list['userId']);
                                bool[list['userId']] = true;
                            }
                        }
                    }

                    let params = new FormData(); //创建一个form对象,必须是form对象否则后端接受不到数据
                    params.append("meetName", this.meetingForm.meetName);
                    params.append("startTimeStr", this.meetingForm.startTime);
                    params.append("type", this.meetingForm.type);
                    if (this.title == '修改会议') {
                        params.append("meetId", this.meetingForm.meetId);
                    }
                    if (this.meetingForm.type == 2) {
                        params.append("participants", this.meetingForm.participants.join(','));
                    } else {
                        params.append("participants", info.join(','));
                    }
                    console.log(this.meetingForm);
                    // httpService("/pythonApi/attendanceApi/addMeeting", params, "post").then(
                    httpService("/javaApi/schoolMeetingList/add", params, "post").then(
                        (data) => {
                            if (data.code == 200) {
                                ElMessage.success('添加成功');
                                this.clear();
                                //刷新父组件的数据
                                this.$parent.getMeetingList();
                            } else {
                                ElMessage.error('添加失败');
                            }
                        }
                    );
                }
            })
        },
        getCheckedKeys(data, keys, key) {
            let res = [];
            recursion(data, false);
            return res;

            function recursion(arr, isChild) {
                let aCheck = [];
                for (let i = 0; i < arr.length; i++) {
                    let obj = arr[i];
                    aCheck[i] = false;
                    if (obj.childrenList) {
                        aCheck[i] = recursion(obj.childrenList, true) ? true : aCheck[i];
                        if (aCheck[i]) {
                            res.push(obj[key]);
                        }
                    }

                    for (let j = 0; j < keys.length; j++) {
                        if (obj[key] == keys[j]) {
                            aCheck[i] = true;
                            if (res.indexOf(obj[key]) == -1) {
                                res.push(obj[key]);
                            }
                            break;
                        }
                    }
                }
                if (isChild) {
                    return aCheck.indexOf(true) != -1;
                }
            }
        },

        fileChange(files) {
            const file = files.raw
            const reader = new FileReader();
            reader.onload = (e) => {
                const data = e.target.result;
                const workbook = XLSX.read(data, { type: 'binary' });
                const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
                const sheetData = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });
                this.meetingForm.participants = sheetData.map(row => row[1]).filter(id => id);
                this.meetingForm.participants.shift()
                this.flag = true
            };
            reader.readAsBinaryString(file);
        },


        // Download() {

        // },


        toExcel() {
            const sheetData = [
                ["序号", "姓名", "曾用名", "人员工号"],
                ["9950", "测试1", "测试1(校)", "230375"],
                ["9951", "测试2", "测试2(正)", "230376"],
                ["9952", "测试3", "测试3(列)", "230377"],
            ]

            // 生成工作表
            let ws = XLSX.utils.aoa_to_sheet(sheetData);

            // 设置边框和样式
            ws = this.setExlStyle(ws);
            // 导出 Excel
            let wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, "分组表");
            const excelData = XLSX.write(wb, { bookType: "xlsx", type: "array" });
            var table = XLSXS.write(wb, {
                type: "buffer"
            });
            try {
                saveAs(
                    new Blob([table], { type: "application/octet-stream" }),
                    `曾用名模版.xlsx`
                );
            } catch (e) {
                if (typeof console !== "undefined") console.log(e, table);
            }
            return table;
        },
        toExcel1() {
            const sheetData = [
                ["姓名", "人员工号"],
                ["测试1", "230375"],
            ]
            // 生成工作表
            let ws = XLSX.utils.aoa_to_sheet(sheetData);

            // 设置边框和样式
            ws = this.setExlStyle(ws);
            // 导出 Excel
            let wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, "分组表");
            const excelData = XLSX.write(wb, { bookType: "xlsx", type: "array" });
            var table = XLSXS.write(wb, {
                type: "buffer"
            });
            try {
                saveAs(
                    new Blob([table], { type: "application/octet-stream" }),
                    `会议人员模版.xlsx`
                );
            } catch (e) {
                if (typeof console !== "undefined") console.log(e, table);
            }
            return table;
        },

        setExlStyle(data) {
            const borderAll = { // 单元格外侧框线
                top: { style: "thin" },
                bottom: { style: "thin" },
                left: { style: "thin" },
                right: { style: "thin" }
            };
            // 获取工作表的范围
            const range = XLSX.utils.decode_range(data["!ref"]);
            for (let R = range.s.r; R <= range.e.r; ++R) {
                for (let C = range.s.c; C <= range.e.c; ++C) {
                    const cellAddress = XLSX.utils.encode_cell({ r: R, c: C });
                    if (!data[cellAddress]) {
                        data[cellAddress] = { v: "" }; // 如果单元格没有内容，设置为空字符串
                    } else {
                        data[cellAddress].s = {
                            border: borderAll, // 添加边框
                            alignment: {
                                horizontal: "center", // 水平居中对齐
                                vertical: "center"    // 垂直居中对齐
                            }
                        };
                    }
                }
            }
            // 设置列宽
            data["!cols"] = [
                { wpx: 115 },
                { wpx: 115 },
                { wpx: 115 },
                { wpx: 115 },
            ];
            return data;
        },


    },
};
</script>
<style></style>